const fs = require("fs");
const express = require("express");
const router = express.Router();

// 引入处理数据的文件
const Student = require("./students");

router.get("/", (req, res) => {
    res.redirect("/students")
});

router.get("/students", (req, res) => {
    Student.findAll(function (err, data) {
        if (err) {
            res.status(500).send("找不到数据")
        }
        res.render("index.html", {
            students: data
        })
    })
});

// 跳转添加页面
router.get("/students/new", (req, res) => {
    res.render("new.html")
});

// 添加的请求
router.post("/add", (req, res) => {
    // 获取表单数据
    // 处理,将数据存在db.json文件中

    console.log(req.body);

    Student.add(req.body, function (err) {
        if (err) {
            return res.status(500).send("存储数据错误")
        }
        res.redirect("/students")
    })

});

router.get("/update", (req, res) => {
    // res.render("edit.html",{
    //     student:
    // })
    Student.findById(parseInt(req.query.id), (err, student) => {
        if (err) {
            return res.status(500).send("数据查找错误")
        }
        // console.log(student)
        res.render("edit.html", {
            student: student
        })
    })
});

router.post("/update", (req, res) => {
    console.log(req.body)
    Student.updateById(req.body, err => {
        if (err) {
            return status(500).send("数据更新失败")
        }
        res.redirect("/")
    })
});

router.get("/delete", (req, res) => {
    var id = req.query.id
    Student.deleteById(req.query.id, err => {
        if (err) {
            return res.status(500).send("删除失败")
        }
        res.redirect("/")
    })
});

module.exports = router;
